package com.bjsxt.base.lockDesign.design2;

import java.util.concurrent.atomic.AtomicReference;

/**
 * 自旋锁--不可重入版
 *
 * SpinReLock去掉部分代码就变成SpinUnReLock了
 */
public class SpinUnReLock {
    private AtomicReference<Thread> owner = new AtomicReference<>();

    public void lock() {
        Thread current = Thread.currentThread();
        // 比SpinReLock少了if (current == owner.get())来绕过自旋, 所以是不可重入
        while (!owner.compareAndSet(null, current)) {
        }
    }

    public void unlock() {
        Thread current = Thread.currentThread();
        owner.compareAndSet(current, null);
    }

}
